<template>
  <a-space
    class="container"
    direction="vertical"
  >
    <!-- // 查询条件 -->
    <a-card>
      <a-form
        :model="searchValue"
        label-align="left"
        auto-label-width
      >
        <a-row class="grid-demo">
          <a-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="6"
            :xl="6"
            :xxl="6"
          >
            <a-form-item
              field="itemText"
              label="名称"
            >
              <a-input
                allow-clear
                v-model="searchValue.itemText"
                placeholder="请输入名称"
              />
            </a-form-item>
          </a-col>

          <a-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="6"
            :xl="6"
            :xxl="6"
            style="margin-left: 20px;"
          >
            <a-form-item
              field="status"
              label="状态"
            >
              <a-select
                placeholder="请选择状态"
                allow-clear
                allow-search
                v-model="searchValue.status"
              >
                <a-option :value="0">启用</a-option>
                <a-option :value="1">禁用</a-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="6"
            :xl="6"
            :xxl="6"
          >
            <a-form-item>
              <a-space>
                <a-button
                  type="primary"
                  @click="search"
                >
                  <template #icon>
                    <icon-search />
                  </template>
                  <span>查询</span>
                </a-button>
                <a-button @click="reset">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  <span>重置</span>
                </a-button>
              </a-space>

            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card>
      <div class="tabletools">
        <a-space>
          <a-button
            type="primary"
            @click="handleAdd"
          >
            <template #icon>
              <icon-plus />
            </template>
            <span>新增</span>
          </a-button>

          <a-button
            status="danger"
            type="primary"
            @click="handleDelAll"
            :disabled="selectedKeys.length === 0"
          >
            <template #icon>
              <icon-delete />
            </template>
            <span>批量删除</span>
          </a-button>

          <a-button
            type="primary"
            status="success"
            @click="returnPath"
          >
            <template #icon>
              <icon-reply />
            </template>
            返回父级
          </a-button>
        </a-space>
      </div>
      <a-table
        style="user-select: none;"
        :span-method="dataSpanMethod"
        :columns='columns'
        :data='data'
        :bordered="tableBorder"
        v-model:selectedKeys="selectedKeys"
        :row-selection="rowSelection"
        :pagination="pagination"
        @page-change="handlePageChange"
        row-key="id"
      >
        <template #index="{record, column, rowIndex}">
          {{ (pagination.current - 1) * pagination.pageSize + rowIndex + 1 }}
        </template>
        <template #status="{record}">
          <a-tag
            color="#f53f3f"
            v-if="record.status === 1"
          >禁用</a-tag>
          <a-tag
            color="#00b42a"
            v-if="record.status === 0"
          >启用</a-tag>
        </template>
        <template #operate="{record}">
          <a-space>
            <a-button
              @click="handleEdit(record)"
              type="primary"
            >编辑</a-button>
            <a-button
              @click="handleDelete(record)"
              type="primary"
              status="danger"
            >删除</a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <add-child
      ref="dictionary"
      @getList="getList"
      :userId="userId"
    />
  </a-space>
</template>
    
<script setup lang="ts">
import { onMounted, ref, reactive, getCurrentInstance } from "vue";
import AddChild from "./AddChild.vue";
import { childList, DelChild } from "@/services/dictionary";
import { tableBorder } from "@/utils/border/table-border.ts";
import { useRoute } from "vue-router";
import { Message, PaginationProps } from "@arco-design/web-vue";
import useModal from "@/hooks/useModal.ts";
import { useRouter } from "vue-router";

const { ModalShow, ModalHide } = useModal();

const router = useRouter();
const returnPath = () => {
  router.push({ name: "dictionary", query: { page, SdictCode, SdictName } });
};
const pagination = reactive<PaginationProps>({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
});

const searchValue = reactive({
  itemText: "",
  status: "",
});
const search = () => {
  current.value = 1;
  selectedKeys.value = [];
  getList();
};
const reset = () => {
  searchValue.itemText = "";
  searchValue.status = "";
  search();
};
const total = ref("");

const selectedKeys = ref([]);
const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: true,
  onlyCurrent: false,
});
// 批量删除
const handleDelAll = () => {
  ModalShow({
    title: "提示",
    content: "您确认要删除选中的字典信息吗？",
  })
    .then(() => {
      DelChild(selectedKeys.value).then((res) => {
        if (res.code === 200) {
          if (data.value.length === 1) {
            current.value = current.value - 1;
          }
          Message.success(res.data);
          getList();
          ModalHide();
          selectedKeys.value = [];
        } else {
          ModalHide();
        }
      });
    })
    .catch(() => {
      Message.info("您取消了删除");
    });
};

const columns = [
  {
    title: "序号",
    dataIndex: "index",
    align: "center",
    slotName: "index",
  },
  {
    title: "父级字典名称",
    dataIndex: "dictName",
    align: "center",
  },
  {
    title: "名称",
    dataIndex: "itemText",
    align: "center",
  },
  {
    title: "值",
    dataIndex: "itemValue",
    align: "center",
  },
  {
    title: "描述",
    dataIndex: "description",
    align: "center",
  },
  {
    title: "箭头颜色",
    dataIndex: "itemColor",
    align: "center",
  },
  {
    title: "排序",
    dataIndex: "sortOrder",
    align: "center",
  },
  {
    title: "状态",
    dataIndex: "status",
    slotName: "status",
    align: "center",
  },
  {
    title: "操作",
    align: "center",
    slotName: "operate",
  },
];

// 合并行
const dataSpanMethod = ({ record, column, rowIndex, columnIndex }) => {

  if (columnIndex === 1) {
    // 只处理第一列 dictName
    const currentValue = record.dictName; //当前单元格的值
    const preRow = rowIndex > 0 ? data.value[rowIndex - 1] : null; //上一行
    const preValue = preRow ? preRow.dictName : null;



    if (currentValue === preValue) {
      return {
        rowspan: 0,
        colspan: 0,
      };
    } else {
      let rowspan = 1;
      for (let i = rowIndex + 1; i < data.value.length; i++) {
        if (data.value[i].dictName === currentValue) {
          rowspan++;
        } else {
          break;
        }
      }
      return {
        rowspan: rowspan,
        colspan: 1,
      };
    }
  }
  return {
    rowspan: 1,
    colspan: 1,
  };
};

// 删除
const id = ref("");
const handleDelete = (row) => {
  id.value = row.id;
  ModalShow({
    title: "提示",
    content: "您确认要删除这条字典信息吗？",
  })
    .then(() => {
      DelChild([id.value]).then((res) => {
        if (res.code === 200) {
          if (data.value.length === 1) {
            current.value = current.value - 1;
          }
          Message.success(res.data);
          getList();
          ModalHide();
        } else {
          ModalHide();
        }
      });
    })
    .catch(() => {
      Message.info("您取消了删除");
    });
};

// 修改
const handleEdit = (row) => {
  dictionary.value?.edit(row);
};
const data = ref([]);

const dictionary = ref<{
  show: () => void;
  edit: (row: any) => void;
}>();

const handleAdd = () => {
  dictionary.value?.show();
};

const current = ref(1);
const pageSize = ref(10); // 每页显示数量

const getList = () => {
  childList({
    current: current.value,
    size: pageSize.value,
    data: {
      dictId: userId, //父级id
      itemText: searchValue.itemText, //名称
      status: searchValue.status, //状态 1启用 0不启用
    },
  }).then((res) => {
    if (res.code === 200) {
      data.value = res.data.records.map((item) => ({
        ...item,
        dictName: dictName, // 添加 dictName
      }));
      total.value = res.data.total;
      pagination.total = res.data.total;
      pagination.current = res.data.current;
      pagination.pageSize = res.data.size;

    }
  });
};
const handlePageChange = (page: number) => {
  current.value = page;
  getList();
};

const route = useRoute();
const userId = route.query.id;
const dictName = route.query.dictName;
const page = route.query.page;
const SdictCode = route.query.SdictCode;
const SdictName = route.query.SdictName;

onMounted(() => {
  getList();
});
</script>
    
<style scoped lang="scss">
.pagination {
  position: absolute;
  bottom: 35px;
  right: 10px;
}
</style>
    